<template>
  <div class="dashboard-container">
    <!-- 顶部数据块 -->
    <el-row :gutter="20" class="mb20" style="display: flex; justify-content: space-between;">
      <el-col :span="4.8" style="flex: 1; min-width: 0; margin: 0 5px;">
        <el-card shadow="hover" class="data-card">
          <div class="data-title">今日订单数</div>
          <div class="data-value">
            <transition name="fade">
              <count-to
                v-if="dataLoaded"
                :start-val="0"
                :end-val="todayOrders"
                :duration="2000"
                :autoplay="true"
              />
            </transition>
          </div>
        </el-card>
      </el-col>
      <el-col :span="4.8" style="flex: 1; min-width: 0; margin: 0 5px;">
        <el-card shadow="hover" class="data-card">
          <div class="data-title">今日营收</div>
          <div class="data-value">
            <transition name="fade">
              <count-to
                v-if="dataLoaded"
                :start-val="0"
                :end-val="todayRevenue"
                :duration="2000"
                :autoplay="true"
                :decimals="2"
                prefix="¥"
              />
            </transition>
          </div>
        </el-card>
      </el-col>
      <el-col :span="4.8" style="flex: 1; min-width: 0; margin: 0 5px;">
        <el-card shadow="hover" class="data-card">
          <div class="data-title">今日收单车辆</div>
          <div class="data-value">
            <transition name="fade">
              <count-to
                v-if="dataLoaded"
                :start-val="0"
                :end-val="todayOrderVehicles"
                :duration="2000"
                :autoplay="true"
              />
            </transition>
          </div>
        </el-card>
      </el-col>
      <el-col :span="4.8" style="flex: 1; min-width: 0; margin: 0 5px;">
        <el-card shadow="hover" class="data-card">
          <div class="data-title">平均客单价</div>
          <div class="data-value">
            <transition name="fade">
              <count-to
                v-if="dataLoaded"
                :start-val="0"
                :end-val="avgOrderValue"
                :duration="2000"
                :autoplay="true"
                :decimals="2"
                prefix="¥"
              />
            </transition>
          </div>
        </el-card>
      </el-col>
      <el-col :span="4.8" style="flex: 1; min-width: 0; margin: 0 5px;">
        <el-card shadow="hover" class="data-card">
          <div class="data-title">累计营收</div>
          <div class="data-value">
            <transition name="fade">
              <count-to
                v-if="dataLoaded"
                :start-val="0"
                :end-val="totalRevenue"
                :duration="2000"
                :autoplay="true"
                :decimals="2"
                prefix="¥"
              />
            </transition>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 营收分析图表 -->
    <el-row :gutter="20" class="mb20">
      <el-col :span="12">
        <el-card shadow="hover" class="chart-card">
          <div slot="header" class="chart-header">
            <span>日营收趋势</span>
            <el-radio-group v-model="dayChartType" size="small">
              <el-radio-button label="week">近7天</el-radio-button>
              <el-radio-button label="month">近30天</el-radio-button>
            </el-radio-group>
          </div>
          <div ref="dayRevenueChart" class="chart-container"></div>
        </el-card>
      </el-col>
      <el-col :span="12">
        <el-card shadow="hover" class="chart-card">
          <div slot="header" class="chart-header">
            <span>月营收趋势</span>
            <el-radio-group v-model="monthChartType" size="small">
              <el-radio-button label="quarter">近3个月</el-radio-button>
              <el-radio-button label="year">近12个月</el-radio-button>
            </el-radio-group>
          </div>
          <div ref="monthRevenueChart" class="chart-container"></div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 时段分析图表 -->
    <el-row :gutter="20">
      <el-col :span="12">
        <el-card shadow="hover" class="chart-card">
          <div slot="header" class="chart-header">
            <span>时段订单分布</span>
          </div>
          <div ref="timeDistributionChart" class="chart-container"></div>
        </el-card>
      </el-col>
      <el-col :span="12">
        <el-card shadow="hover" class="chart-card">
          <div slot="header" class="chart-header">
            <span>时段营收分布</span>
          </div>
          <div ref="timeRevenueChart" class="chart-container"></div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import * as echarts from "echarts";
import dayjs from 'dayjs';
import CountTo from 'vue-count-to';
import { getTodayStatistics, getRevenueTrend, getMonthlyRevenueTrend, getHourlyDistribution, getHourlyRevenue } from '@/api/statistics';

export default {
  components: {
    CountTo
  },
  data() {
    return {
      dataLoaded: false,
      // 顶部数据块数据
      todayOrders: 0,
      todayRevenue: 0,
      todayOrderVehicles: 0,
      avgOrderValue: 0,
      totalRevenue: 0,

      // 图表类型选择
      dayChartType: 'week',
      monthChartType: 'quarter',

      // 图表实例
      dayRevenueChart: null,
      monthRevenueChart: null,
      timeDistributionChart: null,
      timeRevenueChart: null,

      // 添加加载状态标记
      dayChartLoading: false,
      monthChartLoading: false,
      timeDistributionLoading: false,
      timeRevenueLoading: false
    }
  },
  methods: {
    // 生成随机数据
    generateRandomData(count, min, max) {
      return Array.from({ length: count }, () => Math.floor(Math.random() * (max - min + 1)) + min);
    },

    // 初始化顶部数据块
    async initTopData() {
      try {
        const res = await getTodayStatistics();
        if (res.code === 200) {
          this.todayOrders = res.data.todayOrderCount;
          this.todayRevenue = parseFloat(res.data.todayRevenue);
          this.todayOrderVehicles = res.data.todayVehicleCount;
          this.avgOrderValue = parseFloat(res.data.averageOrderPrice);
          this.totalRevenue = parseFloat(res.data.totalRevenue);

          // 延迟显示数据，让动画效果更明显
          setTimeout(() => {
            this.dataLoaded = true;
          }, 100);
        }
      } catch (error) {
        console.error('获取统计数据失败:', error);
        this.$message.error('获取统计数据失败');
      }
    },

    // 初始化日营收图表
    async initDayRevenueChart() {
      try {
        // 设置加载状态，防止重复请求
        if (this.dayChartLoading) return;
        this.dayChartLoading = true;

        const type = this.dayChartType === 'week' ? 7 : 30;
        const res = await getRevenueTrend(type);

        if (res.code === 200 && res.data) {
          this.$nextTick(() => {
            // 安全检查
            if (!this.$refs.dayRevenueChart) {
              this.dayChartLoading = false;
              return;
            }

            // 确保容器已渲染且有尺寸
            setTimeout(() => {
              // 确保组件仍然挂载
              if (!this.$refs.dayRevenueChart) {
                this.dayChartLoading = false;
                return;
              }

              // 重新初始化图表前，先以安全的方式销毁旧实例
              if (this.dayRevenueChart) {
                try {
                  // 先将DOM引用置空再销毁，避免removeChild错误
                  this.dayRevenueChart.getDom = function() {
                    return null;
                  };
                  this.dayRevenueChart.dispose();
                } catch (e) {
                  // 静默处理错误
                }
                this.dayRevenueChart = null;
              }

              // 强制清空容器内容
              const container = this.$refs.dayRevenueChart;
              container.innerHTML = '';

              // 确保数据格式正确
              let dateList = [];
              let revenueList = [];

              // 检查返回的数据格式
              if (Array.isArray(res.data)) {
                dateList = res.data.map(item => item.date || '');
                revenueList = res.data.map(item => parseFloat(item.revenue || 0));
              } else if (res.data.dateList && res.data.revenueList) {
                dateList = res.data.dateList;
                revenueList = res.data.revenueList.map(item => parseFloat(item));
              }

              try {
                // 强制设置容器高度
                container.style.height = '350px';

                // 创建新图表
                const chart = echarts.init(container);

                const option = {
                  tooltip: {
                    trigger: 'axis',
                    formatter: function(params) {
                      return params[0].name + '<br/>' +
                            params[0].seriesName + ': ¥' + params[0].value.toFixed(2);
                    }
                  },
                  grid: {
                    top: 30,
                    bottom: 30,
                    left: 40,
                    right: 20,
                    containLabel: true
                  },
                  xAxis: {
                    type: 'category',
                    data: dateList
                  },
                  yAxis: {
                    type: 'value',
                    name: '营收(元)',
                    axisLabel: {
                      formatter: function(value) {
                        return '¥' + value.toFixed(2);
                      }
                    }
                  },
                  series: [{
                    name: '日营收',
                    data: revenueList,
                    type: 'line',
                    smooth: true,
                    areaStyle: {
                      opacity: 0.1
                    }
                  }]
                };

                // 显式设置图表尺寸
                chart.resize({ width: container.offsetWidth, height: container.offsetHeight });
                chart.setOption(option, true);
                this.dayRevenueChart = chart;
              } catch (e) {
                // 静默处理错误
              } finally {
                // 无论成功失败都重置加载状态
                this.dayChartLoading = false;
              }
            }, 300); // 延迟一点时间确保DOM完全渲染
          });
        } else {
          this.dayChartLoading = false;
        }
      } catch (error) {
        this.dayChartLoading = false;
      }
    },

    // 初始化月营收图表
    async initMonthRevenueChart() {
      try {
        if (this.monthChartLoading) return;
        this.monthChartLoading = true;

        const type = this.monthChartType === 'quarter' ? 3 : 12;
        const res = await getMonthlyRevenueTrend(type);

        if (res.code === 200 && res.data) {
          this.$nextTick(() => {
            if (!this.$refs.monthRevenueChart) {
              this.monthChartLoading = false;
              return;
            }

            setTimeout(() => {
              if (!this.$refs.monthRevenueChart) {
                this.monthChartLoading = false;
                return;
              }

              if (this.monthRevenueChart) {
                try {
                  this.monthRevenueChart.getDom = function() {
                    return null;
                  };
                  this.monthRevenueChart.dispose();
                } catch (e) {
                  // 静默处理错误
                }
                this.monthRevenueChart = null;
              }

              const container = this.$refs.monthRevenueChart;
              container.innerHTML = '';
              container.style.height = '350px';

              try {
                const chart = echarts.init(container);

                const monthList = res.data.map(item => item.month);
                const revenueList = res.data.map(item => parseFloat(item.revenue));

                const option = {
                  tooltip: {
                    trigger: 'axis',
                    formatter: function(params) {
                      return params[0].name + '<br/>' +
                            params[0].seriesName + ': ¥' + params[0].value.toFixed(2);
                    }
                  },
                  grid: {
                    top: 30,
                    bottom: 30,
                    left: 40,
                    right: 20,
                    containLabel: true
                  },
                  xAxis: {
                    type: 'category',
                    data: monthList
                  },
                  yAxis: {
                    type: 'value',
                    name: '营收(元)',
                    axisLabel: {
                      formatter: function(value) {
                        return '¥' + value.toFixed(2);
                      }
                    }
                  },
                  series: [{
                    name: '月营收',
                    data: revenueList,
                    type: 'bar',
                    barWidth: '60%'
                  }]
                };

                chart.resize({ width: container.offsetWidth, height: container.offsetHeight });
                chart.setOption(option, true);
                this.monthRevenueChart = chart;
              } catch (e) {
                // 静默处理错误
              } finally {
                this.monthChartLoading = false;
              }
            }, 300);
          });
        } else {
          this.monthChartLoading = false;
        }
      } catch (error) {
        this.monthChartLoading = false;
      }
    },

    // 初始化时段分布图表
    async initTimeDistributionChart() {
      try {
        if (this.timeDistributionLoading) return;
        this.timeDistributionLoading = true;

        const res = await getHourlyDistribution();

        if (res.code === 200 && res.data) {
          this.$nextTick(() => {
            if (!this.$refs.timeDistributionChart) {
              this.timeDistributionLoading = false;
              return;
            }

            setTimeout(() => {
              if (!this.$refs.timeDistributionChart) {
                this.timeDistributionLoading = false;
                return;
              }

              if (this.timeDistributionChart) {
                try {
                  this.timeDistributionChart.getDom = function() {
                    return null;
                  };
                  this.timeDistributionChart.dispose();
                } catch (e) {
                  // 静默处理错误
                }
                this.timeDistributionChart = null;
              }

              const container = this.$refs.timeDistributionChart;
              container.innerHTML = '';
              container.style.height = '350px';

              try {
                const chart = echarts.init(container);

                const timeSlots = res.data.map(item => item.timeSlot);
                const orderCounts = res.data.map(item => item.orderCount);
                const percentages = res.data.map(item => item.percentage);

                const option = {
                  tooltip: {
                    trigger: 'axis',
                    formatter: function(params) {
                      const orderCount = params[0].value;
                      const percentage = percentages[params[0].dataIndex];
                      return params[0].name + '时段<br/>' +
                            '订单数: ' + orderCount + '<br/>' +
                            '占比: ' + percentage.toFixed(2) + '%';
                    }
                  },
                  grid: {
                    top: 30,
                    bottom: 30,
                    left: 40,
                    right: 20,
                    containLabel: true
                  },
                  xAxis: {
                    type: 'category',
                    data: timeSlots,
                    axisLabel: {
                      interval: 0,
                      rotate: 45
                    }
                  },
                  yAxis: [
                    {
                      type: 'value',
                      name: '订单数',
                      position: 'left'
                    }
                  ],
                  series: [
                    {
                      name: '订单数',
                      type: 'bar',
                      data: orderCounts,
                      barWidth: '40%',
                      itemStyle: {
                        color: '#409EFF'
                      },
                      label: {
                        show: true,
                        position: 'top',
                        formatter: function(params) {
                          return params.value;
                        }
                      }
                    }
                  ]
                };

                chart.resize({ width: container.offsetWidth, height: container.offsetHeight });
                chart.setOption(option, true);
                this.timeDistributionChart = chart;
              } catch (e) {
                // 静默处理错误
              } finally {
                this.timeDistributionLoading = false;
              }
            }, 300);
          });
        } else {
          this.timeDistributionLoading = false;
        }
      } catch (error) {
        this.timeDistributionLoading = false;
      }
    },

    // 初始化时段营收图表
    async initTimeRevenueChart() {
      try {
        if (this.timeRevenueLoading) return;
        this.timeRevenueLoading = true;

        const res = await getHourlyRevenue();

        if (res.code === 200 && res.data) {
          this.$nextTick(() => {
            if (!this.$refs.timeRevenueChart) {
              this.timeRevenueLoading = false;
              return;
            }

            setTimeout(() => {
              if (!this.$refs.timeRevenueChart) {
                this.timeRevenueLoading = false;
                return;
              }

              if (this.timeRevenueChart) {
                try {
                  this.timeRevenueChart.getDom = function() {
                    return null;
                  };
                  this.timeRevenueChart.dispose();
                } catch (e) {
                  // 静默处理错误
                }
                this.timeRevenueChart = null;
              }

              const container = this.$refs.timeRevenueChart;
              container.innerHTML = '';
              container.style.height = '350px';

              try {
                const chart = echarts.init(container);

                const timeSlots = res.data.map(item => item.timeSlot);
                const revenues = res.data.map(item => parseFloat(item.revenue));
                const percentages = res.data.map(item => item.percentage);

                const option = {
                  tooltip: {
                    trigger: 'axis',
                    formatter: function(params) {
                      const revenue = params[0].value;
                      const percentage = percentages[params[0].dataIndex];
                      return params[0].name + '时段<br/>' +
                            '营收: ¥' + revenue.toFixed(2) + '<br/>' +
                            '占比: ' + percentage.toFixed(2) + '%';
                    }
                  },
                  grid: {
                    top: 30,
                    bottom: 30,
                    left: 40,
                    right: 20,
                    containLabel: true
                  },
                  xAxis: {
                    type: 'category',
                    data: timeSlots,
                    axisLabel: {
                      interval: 0,
                      rotate: 45
                    }
                  },
                  yAxis: [
                    {
                      type: 'value',
                      name: '营收(元)',
                      position: 'left',
                      axisLabel: {
                        formatter: function(value) {
                          return '¥' + value.toFixed(2);
                        }
                      }
                    }
                  ],
                  series: [
                    {
                      name: '营收',
                      type: 'bar',
                      data: revenues,
                      barWidth: '40%',
                      itemStyle: {
                        color: '#67C23A'  // 使用绿色表示营收
                      },
                      label: {
                        show: true,
                        position: 'top',
                        formatter: function(params) {
                          return '¥' + params.value.toFixed(2);
                        }
                      }
                    }
                  ]
                };

                chart.resize({ width: container.offsetWidth, height: container.offsetHeight });
                chart.setOption(option, true);
                this.timeRevenueChart = chart;
              } catch (e) {
                // 静默处理错误
              } finally {
                this.timeRevenueLoading = false;
              }
            }, 300);
          });
        } else {
          this.timeRevenueLoading = false;
        }
      } catch (error) {
        this.timeRevenueLoading = false;
      }
    },

    // 添加重绘图表的方法
    resizeCharts() {
      if (this.dayRevenueChart) this.dayRevenueChart.resize();
      if (this.monthRevenueChart) this.monthRevenueChart.resize();
      if (this.timeDistributionChart) this.timeDistributionChart.resize();
      if (this.timeRevenueChart) this.timeRevenueChart.resize();
    }
  },
  watch: {
    dayChartType() {
      this.initDayRevenueChart();
    },
    monthChartType() {
      this.initMonthRevenueChart();
    }
  },
  mounted() {
    this.initTopData();

    // 将图表初始化移到nextTick内
    this.$nextTick(() => {
      this.initDayRevenueChart();
      this.initMonthRevenueChart();
      this.initTimeDistributionChart();
      this.initTimeRevenueChart();

      // 添加窗口大小变化时重绘图表
      window.addEventListener('resize', this.resizeCharts);
    });
  },
  beforeDestroy() {
    // 组件销毁前移除监听器
    window.removeEventListener('resize', this.resizeCharts);

    // 安全销毁图表实例
    const charts = [
      'dayRevenueChart',
      'monthRevenueChart',
      'timeDistributionChart',
      'timeRevenueChart'
    ];

    charts.forEach(chartName => {
      if (this[chartName]) {
        try {
          // 先将DOM引用置空再销毁，避免removeChild错误
          this[chartName].getDom = function() {
            return null;
          };
          this[chartName].dispose();
        } catch (e) {
          // 静默处理错误
        }
        this[chartName] = null;
      }
    });
  }
}
</script>

<style lang="scss" scoped>
.dashboard-container {
  padding: 20px;
  background-color: #f0f2f5;
  min-height: 100vh;
  width: 100%;
  box-sizing: border-box;
}

.data-card {
  text-align: center;
  padding: 15px 0;
  transition: all 0.3s;
  border-radius: 8px;
  border: none;
  background: linear-gradient(135deg, #ffffff 0%, #f8f9fa 100%);
  height: 100%;

  &:hover {
    transform: translateY(-5px);
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  }

  .data-title {
    font-size: 13px;
    color: #666;
    margin-bottom: 8px;
  }

  .data-value {
    font-size: 24px;
    font-weight: bold;
    color: #333;
    margin-bottom: 8px;
    min-height: 32px;
    display: flex;
    justify-content: center;
    align-items: center;
  }
}

.chart-card {
  border-radius: 8px;
  border: none;
  transition: all 0.3s;
  background: linear-gradient(135deg, #ffffff 0%, #f8f9fa 100%);

  &:hover {
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  }

  .chart-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 0 10px;

    span {
      font-size: 16px;
      font-weight: bold;
      color: #333;
    }
  }

  .chart-container {
    height: 350px;
    padding: 10px;
    width: 100%;
  }
}

.el-card {
  margin-bottom: 20px;

  .el-card__header {
    padding: 15px 20px;
    border-bottom: 1px solid #ebeef5;
  }
}

.mb20 {
  margin-bottom: 20px;
}

// 响应式布局
@media screen and (max-width: 1200px) {
  .data-card {
    .data-value {
      font-size: 24px;
    }
  }
}

@media screen and (max-width: 768px) {
  .dashboard-container {
    padding: 10px;
  }

  .data-card {
    .data-value {
      font-size: 20px;
    }
  }
}

.fade-enter-active,
.fade-leave-active {
  transition: opacity 0.5s;
}

.fade-enter,
.fade-leave-to {
  opacity: 0;
}
</style>
